#!/usr/bin/python
import os
import sys
import re
import pylab
import argparse
import shutil

class gui():
    def __init__(self,guiFileName):
        self.name=guiFileName
        self.namePrefix=guiFileName.replace('.gui','')
        nameList=self.name.split('_')
        self.coord=[]
        if len(nameList)==4:
            self.serialNumber=nameList[0].replace('SCAN','')
            self.freq=nameList[1]
            self.disp=nameList[3]
        self.vecta=[]
        self.vectb=[]
        self.vectc=[]
        
    def readgui(self):
        gui=open(self.name,'r')
        count=0
        for line in gui:
            count=count+1
            if count==2:
                self.vecta=map(float,line.split())
            if count==3:
                self.vectb=map(float,line.split())
            if count==4:
                self.vectc=map(float,line.split())
            if len(line.split())==4:
                self.coord.append(line)
        self.numOfAtoms=len(self.coord)
        #convert catersian coordinate to fraction coordinate
        cellCoord=pylab.mat([self.vecta,self.vectb,self.vectc])
        self.newCoord=[]
        for line in self.coord:
            cartCoord=pylab.mat(map(float,line.split()[1:]))
            fracCoord=pylab.array(cartCoord*cellCoord**-1)[0]
            newFracCoord=[]
            for i in fracCoord:
                if i < 0 or i > 1:
                    i=i%1
                newFracCoord.append(i)
            newCartCoord=pylab.array(pylab.mat(newFracCoord)*cellCoord)[0]
            self.newCoord.append("%-5s%-20.12f%-20.12f%-20.12f\n" % (line.split()[0],list(newCartCoord)[0],list(newCartCoord)[1],list(newCartCoord)[2]))
             

    def writeXYZ(self):
        xyzFileName=self.namePrefix+'.xyz'
        xyz=open(xyzFileName,'w')
        xyz.write(str(self.numOfAtoms)+'\n')
        xyz.write(self.serialNumber+' '+self.freq+' '+self.disp+'\n')
        for i in self.newCoord:
            xyz.write(i)
        
            
                   


testgui=gui('naph121_m062x_sto-3g_2.gui')
testgui.readgui()
testgui.writeXYZ()